import cv2
import numpy as np
def get_letter_regions(image_path):
    # 读取图像
    image = cv2.imread(image_path)
    image = cv2.resize(image, (680, 480))
    # 转为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 进行二值化处理
    _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
    # 寻找轮廓
    contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    letter_regions = []
    # 遍历轮廓并裁剪出字母区域
    print("轮廓数量：",len(contours))
    contour_filter=0
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        # 根据实际情况调整裁剪参数，确保裁剪出字母区域
        if w > 50 and h > 50:
            letter_regions.append(image[y:y + h, x:x + w])
        #将轮廓画出来
            cv2.drawContours(image, [contour], -1, (0, 255, 0), 2)
            contour_filter+=1
    print("过滤后的数量：",contour_filter)
    return letter_regions


images=get_letter_regions("C.jpg")
count=0
for img in images:
    cv2.imshow(f"output{count}",img)
    count+=1
cv2.waitKey(0)